﻿using System;
using System.Collections.Generic;
namespace IFramework
{
    public class FactoryManager : Singleton<FactoryManager>
    {
        private Dictionary<Type, IFactory> factorys;
        public override void OnSingletonInit()
        {
            factorys = new Dictionary<Type, IFactory>();
        }
        public override void Dispose()
        {
            factorys.Clear();
            factorys = null;
        }

        public void InsertFactory(IFactory factory)
        {
            CheckDictinaryKey(factory.GetType(), factory);
        }

        public T CreateInstance<T>(IFactory factory, params object[] args) where T : FactoryItem, new()
        {
            CheckDictinaryKey(factory.GetType(), factory);
            return factory.CreateInstance<T>(args);
        }
        private void CheckDictinaryKey(Type type, IFactory factory)
        {
            if (!factorys.ContainsKey(type))
            {
                factorys.Add(type, factory);
            }
            else if (factorys[type] != factory)
            {
                factorys[type] = factory;
            }
        }
    }
}